//
//  NSDate+DDAddition.m
//  IOSDuoduo
//
//  Created by abc on 14-6-5.
//  Copyright (c) 2014年 dujia. All rights reserved.
//

#import "NSDate+DDAddition.h"

static int localAndServerGap = 0;


@implementation NSDate (DDAddition)

- (NSString *)transformDateForIOA
{
    NSDate* nowDate = [NSDate date];
    
    NSCalendar *greCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    [greCalendar setFirstWeekday:2];//设定从星期一开始
    //  通过已定义的日历对象，获取某个时间点的NSDateComponents表示，并设置需要表示哪些信息（NSYearCalendarUnit, NSMonthCalendarUnit, NSDayCalendarUnit等）
    NSDateComponents *nowDateComponents = [greCalendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekCalendarUnit | NSWeekdayCalendarUnit | NSWeekOfMonthCalendarUnit | NSWeekOfYearCalendarUnit fromDate:nowDate];
    
    NSDateComponents *selfDateComponents = [greCalendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekCalendarUnit | NSWeekdayCalendarUnit | NSWeekOfMonthCalendarUnit | NSWeekOfYearCalendarUnit fromDate:self];
    
    NSDateComponents *weeDateComponents = [[NSDateComponents alloc] init];
    [weeDateComponents setCalendar:[NSCalendar currentCalendar]];
    weeDateComponents.year = selfDateComponents.year;
    weeDateComponents.month = selfDateComponents.month;
    weeDateComponents.day = selfDateComponents.day;
    weeDateComponents.hour = 0;
    weeDateComponents.minute = 0;
    weeDateComponents.second = 0;
    
    if (nowDateComponents.year == selfDateComponents.year) {
        //同一年
        if (nowDateComponents.month == selfDateComponents.month) {
            //同一个月
            if (nowDateComponents.day == selfDateComponents.day) {
                //同一天
                NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
                [dateFormatter setDateFormat:@"HH:mm"];
                NSString* dateString = [dateFormatter stringFromDate:self];
                return dateString;
            } else if (nowDateComponents.day -1 == selfDateComponents.day){
                //昨天
                NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
                [dateFormatter setDateFormat:@"HH:mm"];
                NSString* dateString = [dateFormatter stringFromDate:self];
                NSString *string = [NSString stringWithFormat:@"昨天 %@",dateString];
                return string;
            } else {
                if (nowDateComponents.weekOfYear == selfDateComponents.weekOfYear) {
                    NSArray* weekdays = @[@"temp",@"星期日",@"星期一",@"星期二",@"星期三",@"星期四",@"星期五",@"星期六"];
                    NSString* dateString = weekdays[selfDateComponents.weekday];
                    return dateString;
                }else {
                    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
                    [dateFormatter setDateFormat:@"MM月dd日"];
                    NSString* dateString = [dateFormatter stringFromDate:self];
                    return dateString;
                }
            }
        } else {
            NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"MM月dd日"];
            NSString* dateString = [dateFormatter stringFromDate:self];
            return dateString;
        }
    } else {
        NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy年MM月dd日"];
        NSString* dateString = [dateFormatter stringFromDate:self];
        return dateString;
    }
}

//时间提示字符串，聊天窗口中的
- (NSString *)promptDateString {
    NSDate* nowDate = [NSDate date];
    
    NSCalendar *greCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    //  通过已定义的日历对象，获取某个时间点的NSDateComponents表示，并设置需要表示哪些信息（NSYearCalendarUnit, NSMonthCalendarUnit, NSDayCalendarUnit等）
    NSDateComponents *nowDateComponents = [greCalendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekCalendarUnit | NSWeekdayCalendarUnit | NSWeekOfMonthCalendarUnit | NSWeekOfYearCalendarUnit fromDate:nowDate];
    
    NSDateComponents *selfDateComponents = [greCalendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekCalendarUnit | NSWeekdayCalendarUnit | NSWeekOfMonthCalendarUnit | NSWeekOfYearCalendarUnit fromDate:self];
    
    NSDateComponents *weeDateComponents = [[NSDateComponents alloc] init];
    [weeDateComponents setCalendar:[NSCalendar currentCalendar]];
    weeDateComponents.year = selfDateComponents.year;
    weeDateComponents.month = selfDateComponents.month;
    weeDateComponents.day = selfDateComponents.day;
    weeDateComponents.hour = 0;
    weeDateComponents.minute = 0;
    weeDateComponents.second = 0;
    
    NSString* lastComponents = nil;
    //    NSString* twoComponent = nil;
    NSInteger hour = selfDateComponents.hour;
  
    if (selfDateComponents.minute < 10) {
        lastComponents = [NSString stringWithFormat:@"%li:0%li",(long)hour,(long)selfDateComponents.minute];
    } else {
        lastComponents = [NSString stringWithFormat:@"%li:%li",(long)hour,(long)selfDateComponents.minute];
    }
    
    NSString* dateString = nil;
    if (nowDateComponents.day == selfDateComponents.day) {//同一天
        dateString = lastComponents;
    } else if (nowDateComponents.year == selfDateComponents.year) {//同一年
        NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"MM-dd"];
        dateString = [NSString stringWithFormat:@"%@ %@",[dateFormatter stringFromDate:self],lastComponents];
    } else {
        NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yy-MM-dd"];
        dateString = [NSString stringWithFormat:@"%@ %@",[dateFormatter stringFromDate:self],lastComponents];
    }
    return dateString;
}

- (NSString *)transformDateForCRMRecord
{
    NSDate* nowDate = [NSDate date];
    
    NSCalendar *greCalendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
    [greCalendar setFirstWeekday:2];//设定从星期一开始
    //  通过已定义的日历对象，获取某个时间点的NSDateComponents表示，并设置需要表示哪些信息（NSYearCalendarUnit, NSMonthCalendarUnit, NSDayCalendarUnit等）
    NSDateComponents *nowDateComponents = [greCalendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSCalendarUnitWeekOfYear | NSCalendarUnitWeekday | NSCalendarUnitWeekOfMonth | NSCalendarUnitWeekOfYear fromDate:nowDate];
    
    NSDateComponents *selfDateComponents = [greCalendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSCalendarUnitWeekOfYear | NSCalendarUnitWeekday | NSCalendarUnitWeekOfMonth | NSCalendarUnitWeekOfYear fromDate:self];
    
    NSDateComponents *weeDateComponents = [[NSDateComponents alloc] init];
    [weeDateComponents setCalendar:[NSCalendar currentCalendar]];
    weeDateComponents.year = selfDateComponents.year;
    weeDateComponents.month = selfDateComponents.month;
    weeDateComponents.day = selfDateComponents.day;
    weeDateComponents.hour = selfDateComponents.hour;
    weeDateComponents.minute = selfDateComponents.minute;
    weeDateComponents.second = selfDateComponents.second;
    
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSMutableString *dateString = [NSMutableString stringWithString:[dateFormatter stringFromDate:self]];
    
    NSArray* weekdays = @[@"temp",@"星期日",@"星期一",@"星期二",@"星期三",@"星期四",@"星期五",@"星期六"];

    [dateString appendFormat:@" %@",weekdays[selfDateComponents.weekday]];
    
    if (nowDateComponents.year == selfDateComponents.year) {
        // 同一年
        if (nowDateComponents.month == selfDateComponents.month) {
            // 同一个月
            if (nowDateComponents.weekOfYear == selfDateComponents.weekOfYear) {
                // 同一星期
                if (nowDateComponents.day == selfDateComponents.day) {
                    // 同一天
                    [dateString appendString:@" (今天)"];
                } else if (nowDateComponents.day -1 == selfDateComponents.day){
                    // 昨天
                    [dateString appendString:@" (昨天)"];
                }
            }
        }
    }
    
    return dateString;
}

- (NSDictionary *)getFirstAndEndDayOfWeek
{
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *firstComp = [cal components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday fromDate:self];
    
    NSInteger weekDay = [firstComp weekday];
    NSInteger day = [firstComp day];
    
    long firstDiff,lastDiff;
    
    if (weekDay == 1)
    {
        firstDiff = -6;
        lastDiff = 0;
    }
    else
    {
        firstDiff = [cal firstWeekday] - weekDay + 1;
        lastDiff = 8 - weekDay;
    }
    
    NSDateComponents *firstDayComp = [cal components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitWeekday  fromDate:self];
    [firstDayComp setDay:day + firstDiff];
    NSDate *firstDayOfWeek = [cal dateFromComponents:firstDayComp];
    
    NSDateComponents *lastDayComp = [cal components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitWeekday   fromDate:self];
    [lastDayComp setDay:day + lastDiff];
    
    NSDate *lastDayOfWeek = [cal dateFromComponents:lastDayComp];
    
    NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
    [myDateFormatter setDateFormat:@"YYYY-MM-dd"];
    NSString *beginString = [myDateFormatter stringFromDate:firstDayOfWeek];
    NSString *endString = [myDateFormatter stringFromDate:lastDayOfWeek];
    NSDictionary *dic = @{@"startTime":beginString?:@"", @"endTime":endString?:@""};
    
    return dic;
}

#pragma mark - 将某个yyyyMMdd日期戳转化成 时间
+ (NSString *)timestampSwitchTime:(NSInteger)timestamp andFormatter:(NSString *)format{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:format];
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:timestamp];
    NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
    return confromTimespStr;
}

#pragma mark - 将某个hh:mm时间戳转化成 时间
+ (NSString *)timestampSwitchShortTime:(NSInteger)timestamp andFormatter:(NSString *)format{

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterNoStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:format];
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:timestamp];
    NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
    return confromTimespStr;
}

+ (NSInteger)timeSwitchTimestamp:(NSString *)formatTime andFormatter:(NSString *)format
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:format];
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate *date = [formatter dateFromString:formatTime];
    //时间转时间戳的方法:
    NSInteger timeSp = [[NSNumber numberWithDouble:[date timeIntervalSince1970]] integerValue];
    return timeSp;
}

#pragma mark - 只获得HH:mm的时间戳
+ (NSInteger)shortTimeSwitchTimestamp:(NSString *)formatTime andFormatter:(NSString *)format
{
    if (!formatTime || !format) return 0;
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd";
    NSString *strTodayTmp = [formatter stringFromDate:[NSDate date]];
    NSString *strToday = [NSString stringWithFormat:@"%@ %@", strTodayTmp, formatTime];
    NSInteger iTodayStamp = [NSDate timeSwitchTimestamp:strTodayTmp andFormatter:@"yyyy-MM-dd"];
    NSString *strFormat = [NSString stringWithFormat:@"%@ %@", @"yyyy-MM-dd", format];
    NSInteger iPlanStamp = [NSDate timeSwitchTimestamp:strToday andFormatter:strFormat];
    return (iPlanStamp - iTodayStamp);
}

#pragma mark - 转换字符串时间格式
+ (NSString *)timeSwith:(NSString *)formatTime andFormatter:(NSString *)format andNewFormatter:(NSString *)newFormat
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:format];
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];

    NSDate *confromTimesp = [formatter dateFromString:formatTime];
    [formatter setDateFormat:newFormat];
    NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
    return confromTimespStr;
}


- (NSDictionary *)getFirstAndEndDayOfMonth
{
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *firstComp = [cal
                                   components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay
                                   fromDate:self];
    
    NSDateComponents *endCom = [cal
                                components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay
                                fromDate:self];
    
    firstComp.day = 1;
    
    NSRange range = [cal rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:self];
    NSUInteger numberOfDaysInMonth = range.length;
    
    endCom.day = numberOfDaysInMonth;
    
    NSDate *beginDate = [cal dateFromComponents:firstComp];
    NSDate *endDate = [cal dateFromComponents:endCom];
    
    NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
    [myDateFormatter setDateFormat:@"YYYY-MM-dd"];
    NSString *beginString = [myDateFormatter stringFromDate:beginDate];
    NSString *endString = [myDateFormatter stringFromDate:endDate];
    NSDictionary *dic = @{@"startTime":beginString?:@"", @"endTime":endString?:@""};
    
    return dic;
}

- (NSDictionary *)getFirstAndEndDayOfQuarter
{
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *firstComp = [cal
                                   components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay
                                   fromDate:self];
    NSDateComponents *endCom = [cal
                                components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay
                                fromDate:self];
    if (firstComp.month <=3) {
        firstComp.month =  1;
        endCom.month = 3;
    }  else if(firstComp.month<=6) {
        firstComp.month =  4;
        endCom.month = 6;
    }else if(firstComp.month<=9) {
        firstComp.month =  7;
        endCom.month = 9;
    } else if(firstComp.month<=12)  {
        firstComp.month =  10;
        endCom.month = 12;
    }
    
    NSInteger endMonDays = [self howManyDaysInThisYear:firstComp.year withMonth:endCom.month];
    firstComp.day = 1;
    endCom.day = endMonDays;
    
    NSDate *beginDate = [cal dateFromComponents:firstComp];
    NSDate *endDate = [cal dateFromComponents:endCom];
    
    NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
    [myDateFormatter setDateFormat:@"YYYY-MM-dd"];
    NSString *beginString = [myDateFormatter stringFromDate:beginDate];
    NSString *endString = [myDateFormatter stringFromDate:endDate];
    NSDictionary *dic = @{@"startTime":beginString?:@"", @"endTime":endString?:@""};
    
    return dic;
}

- (NSDictionary *)getFirstAndEndDayOfYear
{
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *firstComp = [cal
                                   components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay
                                   fromDate:self];
    NSDateComponents *endCom = [cal
                                components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay
                                fromDate:self];
    firstComp.day = 1;
    firstComp.month = 1;
    endCom.month = 12;
    
    NSInteger endMonDays = [self howManyDaysInThisYear:firstComp.year withMonth:endCom.month];
    firstComp.day = 1;
    endCom.day = endMonDays;
    
    NSDate *beginDate = [cal dateFromComponents:firstComp];
    NSDate *endDate = [cal dateFromComponents:endCom];
    
    NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
    [myDateFormatter setDateFormat:@"YYYY-MM-dd"];
    NSString *beginString = [myDateFormatter stringFromDate:beginDate];
    NSString *endString = [myDateFormatter stringFromDate:endDate];
    NSDictionary *dic = @{@"startTime":beginString?:@"", @"endTime":endString?:@""};
    
    return dic;
}

#pragma mark - 获取某年某月的天数
- (NSInteger)howManyDaysInThisYear:(NSInteger)year withMonth:(NSInteger)month{
    if((month == 1) || (month == 3) || (month == 5) || (month == 7) || (month == 8) || (month == 10) || (month == 12))
        return 31 ;
    
    if((month == 4) || (month == 6) || (month == 9) || (month == 11))
        return 30;
    
    if((year % 4 == 1) || (year % 4 == 2) || (year % 4 == 3))
    {
        return 28;
    }
    
    if(year % 400 == 0)
        return 29;
    
    if(year % 100 == 0)
        return 28;
    
    return 29;
}


/**
 * 计算上次日期距离现在多久
 *
 * @param lastTimeStr  上次日期(需要和格式对应)
 * @param format1   上次日期格式
 * @param currentTimeStr 最近日期(需要和格式对应)
 * @param format2   最近日期格式
 *
 * @return 多少天
 */

+ (NSInteger)dayBYtimeIntervalFromLastTime:(NSString *)lastTimeStr
                            lastTimeFormat:(NSString *)format1
                             ToCurrentTime:(NSString *)currentTimeStr
                         currentTimeFormat:(NSString *)format2{
    //上次时间
    NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc]init];
    dateFormatter1.dateFormat = format1;
    NSDate *lastTime = [dateFormatter1 dateFromString:lastTimeStr];
    //当前时间
    NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc]init];
    dateFormatter2.dateFormat = format2;
    NSDate *currentTime = [dateFormatter2 dateFromString:currentTimeStr];
    
    
    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
    //上次时间
    NSDate *lastDate = [lastTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:lastTime]];
    //当前时间
    NSDate *currentDate = [currentTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:currentTime]];
    //时间间隔
    NSInteger intevalTime = [currentDate timeIntervalSinceReferenceDate] - [lastDate timeIntervalSinceReferenceDate];
    
    NSInteger day = intevalTime / 60 / 60 / 24;  //差了多少天
    
    return day;
}

+ (NSInteger)dayBytimeIntervalFromLastTime:(NSTimeInterval)lastTime CurrentTime:(NSTimeInterval)currentTime
{
    //时间间隔
    NSInteger intevalTime = lastTime - currentTime;
    NSInteger day = intevalTime / 60 / 60 / 24;  //差了多少天
    
    return day;
}



+ (void)setServerTime:(int)serverTime
{
    int localTime = [[NSDate date] timeIntervalSince1970];
    localAndServerGap = serverTime - localTime;
}

+ (NSUInteger)messageDate
{
    int localDate = [[NSDate date] timeIntervalSince1970];
    return localDate + localAndServerGap;
}
+ (NSString *)getNowTimeTimestampWithFormat:(NSString *)format
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
//    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    [formatter setDateFormat:format];
    
    //设置时区,这个对于时间的处理有时很重要
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate *datenow = [NSDate date];//现在时间
    
    //时间转时间戳的方法:
    NSInteger timeSp = [[NSNumber numberWithDouble:[datenow timeIntervalSince1970]] integerValue];
    NSString *ts = [NSString stringWithFormat:@"%ld000",(long)timeSp];//时间戳的值
    return ts;
}

@end
